<template>
  <div class="content">
    <div class="pageSearchView">
      <SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch"/>
    </div>

    <div class="pageTableView">
      <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="未完成" name="WAITING">
          <div class="pageTableMenuView">
            <div class="pageTableTitle">
              列表信息
              <el-icon>
                <house-icon/>
              </el-icon>
            </div>
            <div class="pageTableButView">
              <el-button :icon="Plus" @click="handleAdd">新建</el-button>
            </div>
          </div>
          <Unfinished :paginationParams="paginationParams" :pageTotal="pageTotal" :taskNoPage="taskNoPage"
                      :onSubmit="onSubmit" :fetchPage="fetchPage" :equipmentData="equipmentData"
                      :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"
                      :handleEdit="handleEdit"
                      :handleDel="handleDel" :faultTypeOptions="faultTypeOptions"/>
        </el-tab-pane>
        <el-tab-pane label="已完成" name="FIXED">
          <div class="pageTableMenuView">
            <div class="pageTableTitle">
              列表信息
              <el-icon>
                <house-icon/>
              </el-icon>
            </div>
          </div>
          <Finish :paginationParams="paginationParams" :pageTotal="pageTotal" :taskNoPage="taskNoPage"
                  :onSubmit="onSubmit" :fetchPage="fetchPage" :equipmentData="equipmentData"
                  :handleSizeChange="handleSizeChange" :faultTypeOptions="faultTypeOptions"
                  :handleCurrentChange="handleCurrentChange"/>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 新建/编辑弹框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width=500>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
<!--        <el-form-item label="维修名称" required prop="name" v-if="['add', 'edit'].includes(dialogType)">-->
<!--          <el-input v-model="form.name" placeholder="请输入维修名称" style="width: 300px"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="维修编码" required prop="code" v-if="['add', 'edit'].includes(dialogType)">-->
<!--          <el-input v-model="form.code" placeholder="请输入维修编码" style="width: 300px"/>-->
<!--        </el-form-item>-->
        <el-form-item label="维修设备" prop="equipmentId" v-if="['add', 'edit'].includes(dialogType)">
          <el-select v-model="form.equipmentId" placeholder="请选择维修设备" filterable style="width: 300px">
            <el-option v-for="item in equipmentData" :key="item.id" :label="item.equipmentName" :value="item.id"/>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="实施角色" prop="executeUserId" v-if="['add', 'edit'].includes(dialogType)">-->
<!--          <el-select v-model="form.executeUserId" placeholder="请选择执行人" filterable style="width: 300px">-->
<!--            <el-option v-for="item in userPersonData" :key="item.id" :label="item.nickname" :value="item.id"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
				<el-form-item label="维修结果" prop="result" v-if="dialogType === 'perform'">
					<el-select v-model="form.result" placeholder="请选择维修结果" clearable style="width: 300px">
						<el-option v-for="(item, index) of result" :key="index" :label="item.label" :value="item.label"/>
					</el-select>
				</el-form-item>
        <el-form-item label="维修人" v-if="dialogType === 'perform'">
          <el-select v-model="form.maintenanceUserId" placeholder="请选择维修人" clearable style="width: 300px">
            <el-option v-for="(item, index) of userPersonData" :key="index" :label="item.nickname" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="故障类型" required prop="malfunctionId">
          <el-tree-select v-model="form.malfunctionId" :data="faultData" check-strictly clearable
                          :render-after-expand="false" :props="{ value: 'id', label: 'name', children: 'children' }"
                          placeholder="请选择故障类型" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="处理方式" v-if="dialogType === 'perform'">
          <el-input v-model="form.handleType" type="textarea" placeholder="请输入处理方式" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="原因分析" v-if="dialogType === 'perform'">
          <el-input v-model="form.causeAnalysis" type="textarea" placeholder="请输入原因分析" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="报修描述" prop="repairDescription" v-if="dialogType === 'perform'">
          <el-input v-model="form.repairDescription" type="textarea" placeholder="请输入报修描述"
                    style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="故障内容" >
          <el-input v-model="form.description" type="textarea" placeholder="请输入故障内容" style="width: 300px"></el-input>
        </el-form-item>


      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import SearchForm from '@/components/SearchForm.vue';
import {useToolData} from '@/hooks/baseData/tooling';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import type {ComponentSize, FormInstance, FormRules} from 'element-plus';
import {computed, onMounted, ref, reactive} from 'vue';
import Unfinished from './unfinished.vue';
import Finish from './finish.vue';
import {
  maintenanceOrderAdd,
  equipmentAll,
  maintenanceOrderPage,
  maintenanceOrderUpdate,
  maintenanceMalfunctionAll
} from '@/api/device/maintain';
import {userPersonAll} from '@/api/device/creatPlan';
import moment from 'moment';

const activeName = ref('WAITING');
const searchParam = ref({});
const userList = ref([])
const searchFields = ref([
  {
    name: 'name',
    label: '维修名称',
    component: 'input',
    placeholder: '',
    class: '!w-[350px]'
  }
]);
const pageTotal = ref(0);
const taskNoPage = ref([]);
const equipmentData = ref([]);
const faultData = ref([]);
const paginationParams = ref({pageSize: 10, current: 1});
const dialogVisible = ref(false);
const dialogTitle = ref('新建');
const dialogType = ref('add');
const form = ref({
  name: '',
  code: '',
  equipmentId: '',
  executeUserId: '',
  malfunctionId: '',
  description: ''
});
const result = ref([
  {label: '已维修'},
  {label: '需报废'},
  {label: '待配件'},
  {label: '待外修'},
  {label: '待厂商处理'},
]);
const formRef = ref<FormInstance>();


const rules = reactive<FormRules<form>>({
  name: [{required: true, message: '请输入维修名称', trigger: 'blur'}],
  code: [{required: true, message: '请输入维修编码', trigger: 'blur'}],
  equipmentId: [{required: true, message: '请选择维修设备', trigger: 'blur'}],
  executeUserId: [{required: true, message: '请选择实施角色', trigger: 'blur'}],
  malfunctionId: [{required: true, message: '请选择故障类型', trigger: 'blur'}],
  description: [{required: true, message: '请输入故障内容', trigger: 'blur'}]
});

const faultTypeOptions = ref([]);

onMounted(() => {
  fetchPage();
  fetchAll();
  fetchFaultTypes();
});
const transformToTree = (data) => {
  const map = new Map();
  const tree = [];

  data.forEach(item => {
    map.set(item.id, {...item, children: []});
  });

  data.forEach(item => {
    if (item.parentId === '0') {
      tree.push(map.get(item.id));
    } else {
      const parent = map.get(item.parentId);
      if (parent) {
        parent.children.push(map.get(item.id));
      }
    }
  });

  return tree;
};

const userPersonData = ref([]);

const fetchAll = () => {
  userPersonAll({}).then(res => {
    userPersonData.value = res.data;
  });
  equipmentAll({}).then(res => {
    equipmentData.value = res.data;
  });
  maintenanceMalfunctionAll({type: 1}).then(res => {
    faultData.value = transformToTree(res.data);
    faultTypeOptions.value = res.data;
  });
};

const fetchPage = (params) => {
  let orderStatusList = ['FIXED']
  if (activeName.value !== 'FIXED') {
    orderStatusList = ['WAITING', 'MAINTAINING']
  }
  maintenanceOrderPage({
    ...paginationParams.value,
    ...searchParam.value,
    orderStatusList,
    // ...params,
    type: 1

  }).then(res => {
    taskNoPage.value = res.data.records;
    pageTotal.value = res.data.total;
  });
};
const handleEdit = (row, type) => {
  console.log(row, 'row')
  if (row.orderStatus === 'WAITING') {
    ElMessageBox.confirm('确认开始吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      row.startTime = moment().format('YYYY-MM-DD HH:mm:ss')
      maintenanceOrderUpdate({...row, orderStatus: 'MAINTAINING'}).then(res => {
        if (res.code === 200) {
          ElMessage.success('已开始');
          fetchPage();
        } else {
          ElMessage.error(res.message);
        }
      });
    }).catch(() => {
    });
    return
  }
  if (type) {
    dialogTitle.value = '维修任务完成确认';
    dialogVisible.value = true;
    form.value = {...row, orderStatus: 'FIXED'};
    dialogType.value = 'perform';
  } else {
    dialogTitle.value = '修改';
    dialogVisible.value = true;
    form.value = {...row};
    dialogType.value = 'edit';

  }

};
const handleDel = () => {

};
const handleAdd = () => {
  dialogTitle.value = '新建';
  dialogVisible.value = true;
  dialogType.value = 'add';
  form.value = {
    equipment: '',
    executeUserId: '',
    faultType: [],
    description: ''

  };
};

const handleSearch = () => {
  fetchPage();
};

const handleClick = (tab, event) => {
  activeName.value = tab.props.name;
  fetchPage({orderStatus: tab.props.name});
};

const onSubmit = (params, callback) => {
  maintenanceOrderUpdate(params).then(res => {
    if (res.code === 200) {
      ElMessage.success('操作成功');
      fetchPage();
      callback();
    } else {
      ElMessage.error(res.message);
    }
  });
};

const handleSizeChange = (val) => {
  paginationParams.value.pageSize = val;
  fetchPage();
};

const handleCurrentChange = (val) => {
  paginationParams.value.current = val;
  fetchPage();
};

const fetchFaultTypes = () => {

};

const handleSubmit = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      form.value.orderStatus = 'MAINTAINING'
      if (form.value.result === '已维修' || form.value.result === '需报废') {
        form.value.orderStatus = 'FIXED'
        form.value.finishTime = moment().format('YYYY-MM-DD HH:mm:ss')
        const startTime = moment(form.value.startTime, 'YYYY-MM-DD HH:mm:ss');
        const finishTime = moment(form.value.finishTime, 'YYYY-MM-DD HH:mm:ss');
        form.value.workHour = finishTime.diff(startTime, 'hours', true).toFixed(3);
      }

      const data = {...form.value, type: 1};
      const url = data?.id ? dialogType.value === 'perform' ?
          maintenanceOrderUpdate : maintenanceOrderUpdate : maintenanceOrderAdd;

      url(data).then(response => {
        if (response.code === 200) {
          if (data?.id) {
            if (dialogType.value === 'perform') {
              ElMessage.success('任务已完成');

            } else {
              ElMessage.success('更新成功');
            }

          } else {
            ElMessage.success('添加成功');
          }
          dialogVisible.value = false;
          fetchPage();
        } else {
          ElMessage.error(response.message);
        }
      });

    } else {
    }
  });

};
</script>

<style scoped>
/* 样式可以根据需要调整 */
</style>